package com.ruoyi.system.interceptor;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Forest.AuthToken;
import com.ruoyi.system.domain.Forest.second.BaseResult;
import com.ruoyi.system.domain.Forest.second.TokenResult;
import com.ruoyi.system.service.QueryTokenClient;
import com.ruoyi.system.service.SecondQueryTokenClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class SecondTokenHeaderInterceptor implements Interceptor<Object> {

    @Resource
    private SecondQueryTokenClient authClient;

    @Autowired
    private RedisCache redisCache;
    @Value("${forest.variables.secondName}")
    private String name;
    @Value("${forest.variables.secondPassword}")
    private String password;

    @Override
    public boolean beforeExecute(ForestRequest request) {

        String token = redisCache.getCacheObject(CacheConstants.IOT_TOKEN);
        if (token == null) {
            BaseResult<TokenResult> authToken = authClient.authToken(this.name, this.password);
            if (authToken != null){
                token = authToken.getData().getToken();
                redisCache.setCacheObject(CacheConstants.IOT_TOKEN,  token, 24, TimeUnit.HOURS);

            }else {
                return false;
            }

        }
        if (StringUtils.isNotEmpty(token)){
            request.addHeader("Authorization", "Bearer " + token);
            return true;
        }
        return false;
    }
}
